package com.xbjtech.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.druid.util.StringUtils;
import com.excel.poi.util.PoiAnalyticalData;
import com.excel.poi.util.PoiUtil;
import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Order;
import com.xbjtech.model.OrderExample;
import com.xbjtech.model.OrderExample.Criteria;
import com.xbjtech.model.excelbean.OrderExcelInputColumnInfo;
import com.xbjtech.model.excelbean.OrderExcelOutputColumnInfo;
import com.xbjtech.model.User;
import com.xbjtech.service.OrderService;
import com.xbjtech.service.SellerService;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {

	@Autowired
	OrderService orderService;
	
	@Autowired
	MessageSource messageSource;
	
	@Autowired
	SellerService sellerService;

	@GetMapping("/list")
	public String list() {
		return "order/list";
	}

	@GetMapping("/listpage")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(required = false, defaultValue = "1") int page,
			@RequestParam(required = false, defaultValue = "10") int rows,
			@RequestParam(value = "query_mobile", required = false) String queryMobile,
			@RequestParam(value = "query_orderId", required = false) Long queryOrderId,
			@RequestParam(value = "query_sellerId", required = false) Long querySellerId,
			@RequestParam(value = "query_beginTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryBeginTime,
			@RequestParam(value = "query_endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryEndTime) {
		log.info("query_mobile-->{}", queryMobile);
		Map<String, Object> map = new HashMap<>();
		OrderExample example = new OrderExample();
		example.setOrderByClause("id desc");
		Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(queryMobile)) {
			criteria.andBuyerMobileLike("%" + queryMobile + "%");
		}
		if (null != queryOrderId) {
			criteria.andIdEqualTo(queryOrderId);
		}
		if (null != querySellerId) {
			criteria.andSellerIdEqualTo(querySellerId);
		}
		if (null != queryBeginTime) {
			criteria.andCreateTimeGreaterThanOrEqualTo(queryBeginTime);
		}
		if (null != queryEndTime) {
			criteria.andCreateTimeLessThan(new Date(queryEndTime.getTime() + 24 * 60 * 60 * 1000));
		}

		List<Order> orders = orderService.selectOrdersPaged(page, rows, example);
		PageInfo<Order> info = new PageInfo<>(orders);
		map.put("total", info.getTotal());
		map.put("rows", info.getList());
		return map;
	}

	@GetMapping("/add")
	public String toAddPage() {
		return "order/add";
	}

	@PostMapping("/save")
	public String save(Order order, RedirectAttributes redirectAttributes, Locale locale) {
		// 服务器端的数据校验
		log.info("order-->{}", order);
		User currentLoginUser = (User) SecurityUtils.getSubject().getPrincipal();
		try {
			if (order.getId() == null) {
				order.setCreateUid(currentLoginUser.getId());
				order.setCreateUname(currentLoginUser.getName());
				order.setCreateTime(new Date());
				order.setState(1);
				order.setSellerName(sellerService.selectById(order.getSellerId()).getName());
				orderService.insert(order);
				// 新增成功
				redirectAttributes.addFlashAttribute("successMessage", messageSource.getMessage("success.msg", null, locale));
			} else {
				// 修改操作
				order.setSellerName(sellerService.selectById(order.getSellerId()).getName());
				orderService.updateOrder(order);
				redirectAttributes.addFlashAttribute("successMessage", messageSource.getMessage("success.msg", null, locale));
			}
		} catch (Exception e) {
			// 新增失败
			log.error("save() throws a exception:{}", e.getMessage());
			redirectAttributes.addFlashAttribute("errorMessage", messageSource.getMessage("error.msg", null, locale));
		}
		return "redirect:/order/list";
	}
	
	@GetMapping("/delete/{id}")
	@ResponseBody
	public Map<String, Object> deleteById(@PathVariable Long id) {
		Map<String, Object> map = new HashMap<>();
		try {
			orderService.deleteById(id);
			map.put("flag", true);
			map.put("message", "删除成功");
		} catch (Exception e) {
			map.put("flag", false);
			map.put("message", "删除失败");
		}
		return map;
	}
	
	@GetMapping("/excelout")
	@ResponseBody
	public String excelout(HttpServletResponse response) {
		//导出
		//1.通过sql查询，查询出需要导出的记录
		//2.mybatis封装成List
		List<Order> orders = orderService.selectOrdersPaged(1, 10000, null);
		
		// jxl poi
		//3.List<Order>转换成Excel文件
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Object> outputInfo = new LinkedList<>();
		//List<Order>  --> List<OrderExcelOutputColumnInfo>
		for (Order o : orders) {
			OrderExcelOutputColumnInfo info = new OrderExcelOutputColumnInfo();
			info.setId(o.getId() + "");
			info.setBuyerAddress(o.getBuyerAddress());
			info.setBuyerCarType(o.getBuyerCarType());
			info.setBuyerMobile(o.getBuyerMobile());
			info.setBuyerName(o.getBuyerName());
			info.setBuyerProduct(o.getBuyerProduct());
			info.setCreateTime(df.format(o.getCreateTime()));
			info.setCreateUname(o.getCreateUname());
			info.setPrice(o.getPrice().setScale(2, RoundingMode.HALF_UP).toString());
			info.setSellerName(o.getSellerName());
			outputInfo.add(info);
		}
		
		try {
			XSSFWorkbook xssfWorkbook = PoiUtil.createXSSFWorkbook("工单", OrderExcelOutputColumnInfo.class, outputInfo);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.addHeader("Content-Disposition", "attachment; filename=" + new String("工单".getBytes(), "ISO8859_1") + ".xlsx");
			xssfWorkbook.write(response.getOutputStream());
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//4.reponse把Excel写到客户端
		return null;
	}
	
	@GetMapping("/toupladpage")
	public String toExcelInputPage() {
		return "order/upload";
	}
	
	@PostMapping("/upload")
	public String upload(@RequestParam("file") MultipartFile afile, RedirectAttributes redirectAttributes) {
		//判断一下afile是否是一个合法的Excel
		//1.excel上传到服务器afile
		//2.解析afile  [afile  --> XSSFWorkbook]
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		try {
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(afile.getInputStream());
			List<Object> analyticPoiExcel = PoiAnalyticalData.AnalyticPoiExcel(xssfWorkbook, OrderExcelInputColumnInfo.class);
			List<Order> orders = new LinkedList<>();
			// 数据校验的问题 如果有问题
			for (Object o : analyticPoiExcel) {
				OrderExcelInputColumnInfo info = (OrderExcelInputColumnInfo) o;
				Order order = new Order();
				order.setBuyerAddress(info.getBuyerAddress());
				order.setBuyerCarType(info.getBuyerCarType());
				order.setBuyerMobile(info.getBuyerMobile());
				order.setBuyerName(info.getBuyerName());
				order.setBuyerProduct(info.getBuyerProduct());
				order.setCreateTime(new Date());
				order.setCreateUid(user.getId());
				order.setCreateUname(user.getName());
				order.setState(1);
				order.setPrice(new BigDecimal(info.getPrice()));
				order.setSellerId(1L);
				order.setSellerName(info.getSellerName());
				orders.add(order);
			}
			orderService.insertOrders(orders);
			redirectAttributes.addFlashAttribute("successMessage", "导入成功");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("errorMessage", "导入失败");
			e.printStackTrace();
		}
		return "redirect:/order/list";
	}
	
	@GetMapping("/edit/{id}")
	public String toEditPage(@PathVariable Long id, Model model) {
		Order order = orderService.selectById(id);
		model.addAttribute("order", order);
		return "order/edit";
	}
	
	@GetMapping("/view/{id}")
	public String view(@PathVariable Long id, Model model) {
		Order order = orderService.selectById(id);
		model.addAttribute("order", order);
		return "order/view";
	}
	
	public static void main(String[] args) {
		// DecimalFormat
		// "#.###,00"
		System.out.println(new BigDecimal(1.11111).setScale(2, RoundingMode.HALF_UP));
	}

}
